package com.gy.paidao.setting;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Html;
import android.text.Spannable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gy.paidao.BaseActivity;
import com.gy.paidao.MainActivity;
import com.gy.paidao.MyApplication;
import com.gy.paidao.R;
import com.gy.paidao.bean.BaseBean;
import com.gy.paidao.person.bean.LoginBean;
import com.gy.paidao.util.AnimUtil;
import com.gy.paidao.util.BezelImageView;
import com.gy.paidao.util.HeaderChangeManager;
import com.gy.paidao.util.LogUtil;
import com.gy.paidao.util.PhotoUtil;
import com.gy.paidao.util.SPHelper;
import com.gy.paidao.util.SelectPicPopupWindow;
import com.gy.paidao.util.SelectPopupListener;
import com.gy.paidao.util.SelectPopupUtil;
import com.gy.paidao.util.SelectTimeUtil;
import com.gy.paidao.util.SelectTtimeListener;
import com.gy.paidao.util.ShowDialogUtil;
import com.gy.paidao.util.Urls;
import com.jky.struct2.http.core.AjaxParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author GY
 * @date 16/2/26
 * @Description:账户设置
 */
public class AccountSetActivity extends BaseActivity {

    private LinearLayout ll_profile_picture, ll_usename, ll_gender, ll_birth_date, ll_country;
    private TextView tv_username, tv_gender, tv_birth_data, tv_country, tv_delete_account;
    private BezelImageView mHeadImage;
    private LoginBean loginBean;

    public static final int SET_NICKNAME = 101;//修改昵称
    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    private File tempFile;// 创建一个以当前时间为名称的文件
    private Drawable drawable;
    private Bitmap bitmap;
    private String tempPath, lastPathSegment;
    private Uri photoUri;// 照片uri
    private SelectPicPopupWindow selectPic;
    private SelectTimeUtil timeUtil;//选择生日
    private SelectPopupUtil popupUtil;//选择器
    private List<List<String>> selectPopData;
    private List<String> genderList, contryList;
    private String userLoginID;
    private String strGender,strContry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentViewRes(R.layout.activity_account_set);
        setViews();
        setData();
    }

    @Override
    protected void initVariable() {
        loginBean = MyApplication.loginBean;
        timeUtil = new SelectTimeUtil(this);
        popupUtil = new SelectPopupUtil(this);
        userLoginID = SPHelper.getInstance(this).getStringData("userLoginID", null);
        selectPopData = new ArrayList<>();
        genderList = new ArrayList<>();
        contryList = new ArrayList<>();
        genderList.add(getString(R.string.set_male));
        genderList.add(getString(R.string.set_female));
        String[] contrys = getResources().getStringArray(R.array.country_code_list);
        for (String str : contrys){
            contryList.add(str);
        }
    }

    @Override
    protected void setTitleViews() {
        titleText.setText(this.getResources().getString(R.string.set_account_setting));
    }

    @Override
    protected void setViews() {
        ll_profile_picture = (LinearLayout) findViewById(R.id.account_set_ll_profile_picture);
        ll_usename = (LinearLayout) findViewById(R.id.account_set_ll_usename);
        ll_gender = (LinearLayout) findViewById(R.id.activity_set_ll_gender);
        ll_birth_date = (LinearLayout) findViewById(R.id.activity_set_ll_birth_date);
        ll_country = (LinearLayout) findViewById(R.id.activity_set_ll_country);
        tv_username = (TextView) findViewById(R.id.account_set_tv_username);
        tv_gender = (TextView) findViewById(R.id.account_set_tv_gender);
        tv_birth_data = (TextView) findViewById(R.id.account_set_tv_birth_data);
        tv_country = (TextView) findViewById(R.id.account_set_tv_country);
        tv_delete_account = (TextView) findViewById(R.id.account_set_tv_delete_account);
        mHeadImage = (BezelImageView) findViewById(R.id.account_set_image_head);

        ll_profile_picture.setOnClickListener(this);
        ll_usename.setOnClickListener(this);
        ll_gender.setOnClickListener(this);
        ll_birth_date.setOnClickListener(this);
        ll_country.setOnClickListener(this);
        tv_delete_account.setOnClickListener(this);


    }

    private void setData() {
        tv_username.setText(loginBean.nickname + "");
        tv_birth_data.setText(loginBean.birthday + "");
        if(!TextUtils.isEmpty(loginBean.country)){
            tv_country.setText(loginBean.country+"");
        }
        if (!TextUtils.isEmpty(loginBean.headPortrait)) {
            ImageLoader.getInstance().displayImage(loginBean.headPortrait, mHeadImage);
        }
        if ("gender_male".equals(loginBean.gender)) {
            tv_gender.setText(R.string.set_male);
        } else if ("gender_female".equals(loginBean.gender)) {
            tv_gender.setText(R.string.set_female);
        }

    }

    @Override
    protected void doClickAction(int viewId) {
        super.doClickAction(viewId);
        switch (viewId) {
            case R.id.title_ll_back:
                finish();
                AnimUtil.pushRightInAndOut(this);
                break;
            case R.id.account_set_ll_profile_picture:
                lastPathSegment = "photo";
                selectPic = new SelectPicPopupWindow(this, itemsOnClick);
                tempFile = new File(Environment.getExternalStorageDirectory(),
                        getPhotoFileName());
                selectPic.showAtLocation(this.getWindow().getDecorView(),
                        Gravity.CENTER, 0, 0);
                break;
            case R.id.account_set_tv_delete_account:
                String content = this.getResources().getString(R.string.set_delete_infor);
                Spannable span = (Spannable) Html.fromHtml(content);
                ShowDialogUtil.showDialog(this, R.string.set_delete_account, span,
                        R.string.yes, R.string.cancel, this);
                break;
            case R.id.dialog_show_money_btn_ok://确认

                break;
            case R.id.account_set_ll_usename://修改昵称
                intent = new Intent(this, SettingContentActivity.class);
                intent.putExtra("title",getString(R.string.set_username));
                intent.putExtra("into",SET_NICKNAME);
                startActivityForResult(intent, SET_NICKNAME);
                AnimUtil.pushLeftInAndOut(this);
                break;
            case R.id.activity_set_ll_birth_date://选择生日
                timeUtil.selectYearMonthDay(this.getWindow().getDecorView(), 0, 1, 1, new SelectTtimeListener() {
                    @Override
                    public void setTime(int year, int month, int day, int hour, int minute) {
                        String birthday = year + "-" + month + "-" + day;
                        tv_birth_data.setText(birthday);
                        dorequestBirthday(birthday);
                    }
                });
                break;
            case R.id.activity_set_ll_gender:
                selectPopData.clear();
                selectPopData.add(genderList);
                popupUtil.selectPopup(this.getWindow().getDecorView(), 1, selectPopData, new SelectPopupListener() {
                    @Override
                    public void selectPopup(List<Integer> list) {
                        LogUtil.e(genderList.get(list.get(0))+"------");
                        strGender = genderList.get(list.get(0));
                        tv_gender.setText(strGender);
                        if(getString(R.string.set_male).equals(strGender)){
                            dorequestGender("gender_male");
                        } else if(getString(R.string.set_female).equals(strGender)){
                            dorequestGender("gender_female");
                        }
                    }
                });
                break;
            case R.id.activity_set_ll_country://选择国家
                selectPopData.clear();
                selectPopData.add(contryList);
                popupUtil.selectPopup(this.getWindow().getDecorView(), 1, selectPopData, new SelectPopupListener() {
                    @Override
                    public void selectPopup(List<Integer> list) {
                        LogUtil.e(contryList.get(list.get(0))+"------");

                        strContry = contryList.get(list.get(0));
                        tv_country.setText(strContry);
                        dorequestContry(strContry);
                    }
                });
                break;
        }
    }

    private void dorequestComplete() {
        showLoading();
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(30, TimeUnit.SECONDS);
        client.setReadTimeout(30, TimeUnit.SECONDS);
        client.setWriteTimeout(30, TimeUnit.SECONDS);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] b = baos.toByteArray();
        RequestBody fileBody = null;
        fileBody = RequestBody.create(MediaType.parse(guessMimeType(lastPathSegment)), b);
        MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM)
                .addPart(Headers.of("Content-Disposition", "form-data; name=\"file\";" +
                        "filename=\"" + "png" + "\""), fileBody);
        Request request = new Request.Builder()
//                .url("http://192.168.1.105:8080/user/uploadHeadPortrait")
                .url("http://123.56.176.252:8080/paidao-services/user/uploadHeadPortrait?")
                .addHeader("Cookie", "userLoginID=" + userLoginID)
                .post(multipartBuilder.build())
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                LogUtil.e("头像上传失败");
                dismissLoading();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                String json = response.body().string();
                LogUtil.e("头像上传成功" + json);
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    String data = jsonObject.optString("data");
                    boolean success = jsonObject.optBoolean("success");
                    if(success){
                        JSONObject dataObject = new JSONObject(data);
                        String url = dataObject.optString("url");
                        MyApplication.loginBean.headPortrait = url;
                        HeaderChangeManager.getInstance().notifyAllListener();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        });
    }

    /**
     * 修改生日
     */
    private void dorequestBirthday(String birthday) {
        showLoading();
        params = new AjaxParams();
        params.put("birthday", birthday + "");
        httpRequest.addHeader("Cookie", "userLoginID=" + userLoginID);
        httpRequest.post(Urls.url_birthday, params, callBack, 0);
    }

    /** 修改性别*/
    private void dorequestGender(String gender){
        showLoading();
        params = new AjaxParams();
        params.put("gender", gender + "");
        httpRequest.addHeader("Cookie", "userLoginID=" + userLoginID);
        httpRequest.post(Urls.url_gender, params, callBack, 1);
    }

    /** 修改国家*/
    private void dorequestContry(String contry){
        showLoading();
        params = new AjaxParams();
        params.put("country", contry + "");
        httpRequest.addHeader("Cookie", "userLoginID=" + userLoginID);
        httpRequest.post(Urls.url_contry, params, callBack, 2);
    }

    @Override
    protected void handlerBean(int requestCode, BaseBean baseBean) {
        super.handlerBean(requestCode, baseBean);
        dismissLoading();
        if (baseBean.success) {
            String data = String.valueOf(baseBean.data);
            switch (requestCode) {
                case 0://修改生日
                    showToast("修改生日成功");
                    MyApplication.loginBean.birthday = tv_birth_data.getText().toString().trim();
                    break;
                case 1:
                    showToast("修改性别成功");
                    MyApplication.loginBean.gender = strGender;
                    break;
                case 2:
                    showToast("修改国家成功");
                    MyApplication.loginBean.country = strContry;
                    break;
            }
        } else {
            if (!TextUtils.isEmpty(baseBean.errMsg)) {
                showToast(baseBean.errMsg);
            }
        }
    }

    private static String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

    // 为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            selectPic.dismiss();
            Intent intent;
            switch (v.getId()) {
                case R.id.pop_select_picture_ll_take:
                    // 调用系统的拍照功能
                    // startCamera();
                    // 调用系统的拍照功能
                    intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    // 指定调用相机拍照后照片的储存路径
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                    startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
                    break;
                case R.id.pop_select_picture_ll_pick:
                    // selectPictrue();
                    intent = new Intent(Intent.ACTION_PICK, null);
                    intent.setDataAndType(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        switch (resultCode){
            case SET_NICKNAME://修改昵称
                String nickname = data.getStringExtra("nickname");
                tv_username.setText(nickname);
                break;
        }
        switch (requestCode) {
            case PHOTO_REQUEST_CUT:
                if (data != null)
                    setPicToView(data);
                break;
            case PHOTO_REQUEST_TAKEPHOTO:
                if (tempFile == null) {
                    showToast("操作失败,请重试...");
                    return;
                }
                tempPath = tempFile.getPath();
                tempFile = null;
                int degree = getBitmapDegree(tempPath);
                bitmap = PhotoUtil.getSizedBitmap(1280, 720, tempPath);
                if (bitmap == null)
                    return;
                bitmap = rotateBitmapByDegree(bitmap, degree);
                if (bitmap != null) {
                    LogUtil.e("1------------");
                    mHeadImage.setImageBitmap(bitmap);
                    dorequestComplete();
                }
                break;

            case PHOTO_REQUEST_GALLERY:
                setImageProve(data);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    // 将进行剪裁后的图片显示到UI界面上
    private void setPicToView(Intent picdata) {
        Bundle bundle = picdata.getExtras();
        if (bundle != null) {
            Bitmap photo = bundle.getParcelable("data");
            bitmap = photo;
            drawable = new BitmapDrawable(photo);
            mHeadImage.setImageDrawable(drawable);
            LogUtil.e("2------------");
        }
    }

    /**
     * 读取图片的旋转的角度
     *
     * @param path
     *            图片绝对路径
     * @return 图片的旋转角度
     */
    private int getBitmapDegree(String path) {
        int degree = 0;
        try {
            // 从指定路径下读取图片，并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(path);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 将图片按照某个角度进行旋转
     *
     * @param bm
     *            需要旋转的图片
     * @param degree
     *            旋转角度
     * @return 旋转后的图片
     */
    public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;

        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }

    private void setImageProve(Intent data) {
        if (data == null) {
            showToast("操作失败,请重试...");
            return;
        }
        photoUri = data.getData();
        try {
            ContentResolver resolver = getContentResolver();

            if (resolver.getType(photoUri) != null
                    && PhotoUtil.isImageFormat(resolver.getType(photoUri))) {

            } else {
                showToast("操作失败,请重试...");
                return;
            }
            Cursor cursor = this.getContentResolver().query(photoUri, null,
                    null, null, null);
            cursor.moveToFirst();
            String path = "";
            try {
                path = cursor.getString(1);
            } catch (Exception e) {
            }
            cursor.close();
            if (PhotoUtil.isImageFormat(resolver.getType(photoUri))) {
            } else {
                InputStream in = resolver.openInputStream(photoUri);
            }
            int degree = getBitmapDegree(path);
            bitmap = PhotoUtil.getSizedBitmap(1280, 720, path);
            if (bitmap == null)
                return;
            bitmap = rotateBitmapByDegree(bitmap, degree);
            mHeadImage.setImageBitmap(bitmap);
            LogUtil.e("3------------");
            dorequestComplete();
        } catch (Exception e) {
            e.printStackTrace();
            showToast("操作失败,请重试...");
            return;
        }
        tempPath = photoUri.getPath();
        if (tempPath == null) {
            showToast("操作失败,请重试...");
            return;
        }
        if (tempPath.endsWith(".jpg") || tempPath.endsWith(".png")
                || tempPath.endsWith(".jpeg")) {

        } else if (!tempPath.startsWith("/mnt/")) {
            String[] proj = {MediaStore.Images.Media.DATA};
            // Sysout.i("img path ===", tempPath);
            Cursor actualimagecursor = managedQuery(photoUri, proj, null, null,
                    null);
            if (actualimagecursor != null) {
                int actual_image_column_index = actualimagecursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                actualimagecursor.moveToFirst();
                tempPath = actualimagecursor
                        .getString(actual_image_column_index);
            } else {
                showToast("操作失败,请重试...");
                return;
            }
        }
    }

    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }

}
